<template>
  <base-popup ref="popupRef" round mode="bottom" :closeable="false">
    <view class="base-datetime-picker">
      <nut-date-picker
        v-model="currentDate"
        :title="props.title"
        :min-date="minDateValue"
        :max-date="maxDateValue"
        :type="props.type"
        :formatter="props.formatter"
        :filter="props.filter"
        :show-toolbar="true"
        @confirm="confirm"
        @cancel="cancel"
      />
    </view>
  </base-popup>
</template>

<script setup>
import BasePopup from "@/components/base-popup/uv-popup.vue";

const emits = defineEmits(["confirm"]);

const props = defineProps({
  title: {
    type: String,
    default: "选择时间"
  },
  minDate: {
    type: [Date, Number, String],
    default: () => new Date(new Date().getFullYear() - 10, 0, 1)
  },
  maxDate: {
    type: [Date, Number, String],
    default: () => new Date(new Date().getFullYear() + 10, 11, 31)
  },
  type: {
    type: String,
    default: "date" // date、time、year-month、month-day、datehour、datetime
  },
  formatter: {
    type: Function,
    default: null
  },
  filter: {
    type: Function,
    default: null
  }
});

const popupRef = ref(null);
const currentDate = ref(new Date());

// 计算属性：确保 minDate 和 maxDate 始终是 Date 对象
const minDateValue = computed(() => {
  if (!props.minDate) return new Date(new Date().getFullYear() - 10, 0, 1);
  return props.minDate instanceof Date ? props.minDate : new Date(props.minDate);
});

const maxDateValue = computed(() => {
  if (!props.maxDate) return new Date(new Date().getFullYear() + 10, 11, 31);
  return props.maxDate instanceof Date ? props.maxDate : new Date(props.maxDate);
});

const confirm = (value) => {
  emits("confirm", {
    value: value.selectedValue,
    detail: value
  });
  cancel();
};

const cancel = () => {
  popupRef.value.close();
};

const open = () => {
  popupRef.value.open();
};

defineExpose({
  open
});
</script>

<style lang="scss">
.base-datetime-picker {
  width: 100vw;
  min-height: 400px;
  max-height: 80vh;
  overflow: auto;
}
</style>
